package com.baizhi.demo1;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.jdbc.Work;

public class UserDAOImpl implements UserDAO {

	@Override
	public void insert(User user) {
		Session session = HibernateUtil.getCurrentSession();
		session.save(user);
	}

	@Override
	public void update(User user) {
		Session session = HibernateUtil.getCurrentSession();
		session.update(user);
		
	}

	@Override
	public void delete(User id) {
		Session session = HibernateUtil.getCurrentSession();
		session.delete(id);
	}

	@Override
	public User selectById(Long id) {
		Session session = HibernateUtil.getCurrentSession();
		User u = (User) session.get(User.class, id);
		return u;
	}

	@Override
	public List<User> selectList() {
		
		Session session = HibernateUtil.getCurrentSession();
		Query query = session.createQuery("from User");
		List<User> users = query.list();
		return users;
	}

	@Override
	public void batchDelete(Long[] ids) {
		
	}

	@Override
	public void batchInsert(List<User> users) {
		// TODO Auto-generated method stub
		Session session = HibernateUtil.getCurrentSession();
		
		/*for (User user : users) {
			session.save(user);
		}*/
		
		session.doWork(new Work() {
			@Override
			public void execute(Connection conn) throws SQLException {
				String insertSQL = "INSERT INTO hibernate.t_user(birth, email, mobile, password, regist_date, status, username, vip) VALUES(?, ?, ?, ?, ?, ?, ?, ?)";
				conn.setAutoCommit(false);
				PreparedStatement pstm = conn.prepareStatement(insertSQL);
				for(int i=0;i<users.size();i++) {
					pstm.setDate(1, DateUtil.toSqlDate(users.get(i).getBirth()));
					pstm.setString(2, users.get(i).getEmail());
					pstm.setString(3, users.get(i).getMobile());
					pstm.setString(4, users.get(i).getPassword());
					pstm.setDate(5, DateUtil.toSqlDate(users.get(i).getRegistDate()));
					pstm.setInt(6, users.get(i).getStatus());
					pstm.setString(7, users.get(i).getUsername());
					pstm.setInt(8, users.get(i).getVip());
					pstm.addBatch();
					if(i%00==0) {
						pstm.executeBatch();
						conn.commit();
					}
				}
				pstm.addBatch();
				pstm.executeBatch();
				conn.commit();
			}
		});
	}
}
